//
//  MyController.m
//  
//
//  Created by 郭明皓 on 15/10/26.
//
//

#import "MyController.h"
#import "GMHDataFiled.h"
#import "MyCell.h"
#import "GMH_CollectionViewController.h"
#import "GMH_HistoryViewController.h"
#import <UIImageView+WebCache.h>
#import "GMH_shopingViewController.h"
#import "GMH_Share.h"
#import "UMSocial.h"

#import "DKNightVersion.h"
#import <MessageUI/MessageUI.h>
#define HEIGHT self.view.frame.size.height
@interface MyController ()<UITableViewDataSource, UITableViewDelegate, MFMailComposeViewControllerDelegate, UIAlertViewDelegate>
@property (nonatomic, retain)UITableView *tableview;
@property (nonatomic, retain)UIView *headerView;
@property (nonatomic, retain)NSArray *arryone;
@property (nonatomic, retain)NSArray *arrytwo;
@property (nonatomic, retain)NSArray *arrythree;
@property (nonatomic, retain)NSArray *arryfour;
@property (nonatomic, retain)UIImageView *images;
@property (nonatomic, retain)UIAlertView *loginAlert;
@property (nonatomic, retain)UISwitch *switchs;

@end

@implementation MyController
- (void)dealloc
{
    [_switchs release];
    [_loginAlert release];
    [_arryfour release];
    [_images release];
    [_arryone release];
    [_arrythree release];
    [_arrytwo release];
    [_headerView release];
    [_tableview release];
    [super dealloc];
}
#pragma  mark -viewwillAppear
- (void)viewWillAppear:(BOOL)animated
{
    self.title = @"我的";
    self.tabBarController.tabBar.hidden = NO;
    [self.tableview reloadData];
    
}
#pragma mark viewDidload
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.nightBarTintColor = UIColorFromRGB(0x444444);
    self.navigationController.navigationBar.translucent = NO;
    

    self.view.backgroundColor = [UIColor whiteColor];
        CGRect rect = CGRectMake(0, 0,
                                 self.view.frame.size.width,
                                 self.view.frame.size.height - 49);
        
        //tableView创建
        self.tableview = [[UITableView alloc]initWithFrame:rect style:UITableViewStyleGrouped];
        [self.view addSubview:self.tableview];
        [_tableview release];
        self.tableview.delegate = self;
        self.tableview.dataSource =self;;
        self.tableview.rowHeight = 40;
        self.view.backgroundColor = [UIColor whiteColor];
    self.tableview.nightBackgroundColor = [UIColor blackColor];
    self.tableview.nightSeparatorColor = [UIColor darkGrayColor];
    
        self.headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, HEIGHT / 4)];
        self.tableview.tableHeaderView = self.headerView;
        [_headerView release];
        
        self.images = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"h3.jpg"]];
        self.images.frame = self.headerView.frame;
        [self.headerView addSubview:self.images];

    
    
    self.arryone = @[@"夜间模式", @"清理缓存"];
    self.arrytwo = @[@"我的收藏", @"浏览历史", @"团购预约"];
    self.arrythree = @[@"分享要出发给朋友", @"检查更新", @"给我们提意见"];
    

    
}


#pragma mark tableView协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"";
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.arryone.count;
    }
    if (section == 1) {
        return self.arrytwo.count;
    }
    if (section == 3) {
        return self.arryfour.count;
    }
    else {
        return self.arrythree.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strs = @"tableView";
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:strs];
    if (!cell) {
        cell = [[MyCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strs];
    }
    if (indexPath.section == 0) {
        cell.leftLabel.text = self.arryone[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
    }
    if (indexPath.section == 1) {
        cell.leftLabel.text = self.arrytwo[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头

    }
    if (indexPath.section == 2) {
         cell.leftLabel.text = self.arrythree[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头

    }

    if (indexPath.section == 3) {
        cell.leftLabel.text  =  self.arryfour[indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头

    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //夜间模式
    if (indexPath.section == 0 && indexPath.row == 0) {
        
        if ([DKNightVersionManager currentThemeVersion] == DKThemeVersionNight) {
            [GMH_Share SingleShare].isNight = NO;//日间模式

            self.view.window.alpha = 1;
            [DKNightVersionManager dawnComing];
            
        } else {
            [DKNightVersionManager nightFalling];
            [GMH_Share SingleShare].isNight = YES;//夜间模式
            self.view.window.alpha = 0.8;
        }
        [self.tableview reloadData];
    }
    //清除缓存
    if (indexPath.section == 0 && indexPath.row == 1) {
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//        NSString *datePath = [cachePath stringByAppendingPathComponent:@"Travel"];
        NSLog(@"%@", cachePath);
        CGFloat cacheSize = [self folderSizeAtPath:cachePath];
        
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"%@%.2fM", @"清除共", cacheSize] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.delegate = self;
        [alert show];
        [self.tableview reloadData];
    }
    //我的收藏
    if (indexPath.section == 1 && indexPath.row == 0) {
        
        
        GMH_CollectionViewController *collect = [[GMH_CollectionViewController alloc]init];
        [self.navigationController pushViewController:collect animated:YES];
        [collect release];

    }
    //浏览历史
    if (indexPath.section == 1 && indexPath.row == 1) {
        
        GMH_HistoryViewController *collect = [[GMH_HistoryViewController alloc]init];
        [self.navigationController pushViewController:collect animated:YES];
        [collect release];
//        collect.hidesBottomBarWhenPushed = YES;
        self.tabBarController.tabBar.hidden = YES;
    }
    //团购预约
    if (indexPath.section == 1 && indexPath.row == 2) {
        self.tabBarController.tabBar.hidden = YES;
        GMH_shopingViewController *shop = [[GMH_shopingViewController alloc]init];
        [self.navigationController pushViewController:shop animated:YES];
        [shop release];

    }
    //分享
    if (indexPath.section == 2 && indexPath.row == 0) {
        self.tabBarController.tabBar.hidden = YES;
        NSLog(@"分享成功");
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"5639a9fd67e58e5fad00119c"
                                          shareText:nil
                                         shareImage:nil
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession, UMShareToEmail, UMShareToSms, UMShareToWechatTimeline, UMShareToTencent,nil]
                                           delegate:nil];

    }
    //检查更新
    if (indexPath.section == 2 && indexPath.row == 1) {
        NSDictionary *dic = [[NSBundle mainBundle] infoDictionary];//获取info－plist
         NSString *appVersion = [dic valueForKey:@"CFBundleVersion"];//获取Bundle Version
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"当前版本为%@", appVersion] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alert show];

    }
    //给我们提意见
    if (indexPath.section == 2 && indexPath.row == 2) {
        //是否有这个类
        Class mailClass = NSClassFromString(@"MFMailComposeViewController");
        if (mailClass) {
            
            if ([mailClass canSendMail]) {
                
                [self displayMailBox];
                
            } else {
                
                [self showMailBoxOnDevice];
            }
        } else {
            [self showMailBoxOnDevice];
            
        }

    }
    
   
}


//提示框的点击事件 //清理缓存
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView == self.loginAlert) {
        if (buttonIndex == 1) {
            self.flag = NO;
            self.mImages = nil;
            self.titlestr = nil;
            [GMH_Share SingleShare].message = 3;
            self.arryfour  = [NSMutableArray array];
            [self viewDidLoad];
            

        }
        [self.tableview reloadData];
    }
    else
    {
        if (buttonIndex == 0) {
            NSLog(@"取消清理缓存");
        }else if (buttonIndex == 1) {
            // 创建一个文件管理者
            NSFileManager *manager = [NSFileManager defaultManager];
            NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            NSLog(@"%@", cachePath);
            [manager removeItemAtPath:cachePath error:nil];
        
        }
    }
    
}
///计算缓存文件的大小的M
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}


#pragma mark 发送邮件
//打开设备自带的邮箱工具
- (void)showMailBoxOnDevice {
    
    NSString *mail = @"254804665@qq.com";
    mail = [mail stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mail]];
    
}
- (void)displayMailBox {
    
    //创建邮件视图VC
    MFMailComposeViewController *mailBox = [[MFMailComposeViewController alloc] init];
    //填写收件人地址
    NSArray *recipient = [NSArray arrayWithObjects:@"254804665@qq.com", nil];
    [mailBox setToRecipients:recipient];
    //填写主题
    [mailBox setSubject:@"意见反馈"];
    //填写邮件内容
    NSString *messageBodu = @"请留下您宝贵的意见:";
    [mailBox setMessageBody:messageBodu isHTML:YES];
    
    //添加一个文件
    UIImage *image = [UIImage imageNamed:@"remember.jpg"];
    NSData *data = UIImagePNGRepresentation(image);
    [mailBox addAttachmentData:data mimeType:@"" fileName:@"remember.jpg"];
    //设置代理人
    mailBox.mailComposeDelegate = self;
    
    [self presentViewController:mailBox animated:YES completion:^{
        
        
    }];
}

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    
    NSString *message;
    switch (result) {
        case MFMailComposeResultCancelled:
            message = @"取消发送";
            NSLog(@"%@", message);
            break;
            
        case MFMailComposeResultSaved:
            message = @"保存草稿";
            NSLog(@"%@", message);
            break;
        case MFMailComposeResultSent:
            message = @"发送成功";
            NSLog(@"%@", message);
            break;
        case MFMailComposeResultFailed:
            message = @"发送失败";
            NSLog(@"%@", message);
            break;
            
        default:
            break;
    }
    
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
